package com.ficus.road.maintain.third.zh.coverage;

import com.alibaba.fastjson.JSONArray;
import com.ficus.road.maintain.core.model.coverage.CycleNum;
import com.ficus.road.maintain.core.model.coverage.CycleNumZH;
import com.ficus.road.maintain.dao.coverage.CycleNumDao;
import com.ficus.road.maintain.third.zh.BaseZH;
import com.ficus.road.maintain.util.MyDateUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @author xiawen yang
 * @date 2022/3/16 下午3:28
 */
@Component
public class ZHCycleNum extends BaseZH {

    @Autowired
    private CycleNumDao cycleNumDao;

    @PostConstruct
    void init() {
        arg0 = "getCycleNum";
        errMsg = "调用中海接口获取考核周期编码异常!";
        successMsg = "调用中海接口获取考核周期编码成功!";
    }

    @Scheduled(cron = "0 0 12,14,16 * * ?", zone = "GMT+8:00")
    public synchronized void refreshCycleNum() {
        String todayStr = MyDateUtil.dateFormatStr(new Date(), "yyyy-MM-dd");
        arg1 = "{\"datetime\":\"" + todayStr + "\"}";
        String cycleNumStr = null;
        int i = 0;
        while (i < 10) {
            cycleNumStr = getZHData();
            if (ObjectUtils.isNotEmpty(cycleNumStr)) {
                break;
            }
            i++;
        }
        if (ObjectUtils.isEmpty(cycleNumStr)) {
            return;
        }
        String cycleNum = JSONArray.parseArray(cycleNumStr, CycleNumZH.class).get(0).getCyclenum();
        CycleNum build = CycleNum.builder().id(todayStr).cycleNum(cycleNum).build();
        cycleNumDao.saveOrUpdate(build);
    }

    public synchronized String getCycleNum(String targetDate) {
        CycleNum fetch = cycleNumDao.fetch(targetDate);
        if (ObjectUtils.isNotEmpty(fetch)) {
            return fetch.getCycleNum();
        }
        arg1 = "{\"datetime\":\"" + targetDate + "\"}";
        String cycleNumStr = null;
        int i = 0;
        while (i < 10) {
            cycleNumStr = getZHData();
            if (ObjectUtils.isNotEmpty(cycleNumStr)) {
                break;
            }
            i++;
        }
        if (ObjectUtils.isEmpty(cycleNumStr)) {
            return null;
        }
        String cycleNum = JSONArray.parseArray(cycleNumStr, CycleNumZH.class).get(0).getCyclenum();
        CycleNum build = CycleNum.builder().id(targetDate).cycleNum(cycleNum).build();
        cycleNumDao.saveOrUpdate(build);
        return cycleNum;
    }

}
